import { availableCarList, carList } from '@/gql/carAuthorized';
import { errorToast, showLoading, showToast, successToast } from '@/utils/prompt';
import { toPublish } from '@mqtt';
import { defineStore } from 'pinia';
import { getDriverID } from './driverID';

export const useVehicleStore = defineStore('vehicle', {
  state: () => ({
    plateList: [],
    vehicleList: [],
  }),
  actions: {
    getPlateList() {
      const payload = {
        query: availableCarList,
        variables: { driver_id: getDriverID() },
      };
      toPublish('ql/driver/cartListCanUse', payload, (obj: any) => {
        const { cart_list_can_use } = obj.data;
        this.plateList = cart_list_can_use === null ? [] : cart_list_can_use.map((v) => v.cart_code);
      });
    },
    getVehicleList() {
      const payload = {
        query: carList,
        variables: {
          from_driver_id: 0,
          driver_id: getDriverID(),
        },
      };
      toPublish('ql/driver/getCartList', payload, (obj: any) => {
        const { cart_list } = obj.data;
        this.vehicleList = cart_list;
      });
    },
    addPlate(plate: string, handler: (msg: string) => void, timeout = () => errorToast('添加车牌超时 请稍候再试')) {
      const payload = {
        driver_id: getDriverID(),
        cart_code: plate,
      };
      toPublish(
        'driver/addCart',
        payload,
        (obj: any) => {
          const { code, msg } = obj;
          if (code === 1) {
            this.getPlateList();
            handler(msg);
          } else {
            errorToast(msg);
          }
        },
        timeout,
      );
    },
    removeVehicle(id: number) {
      const payload = {
        id,
        driver_id: getDriverID(),
      };
      toPublish('driver/delCart', payload, (obj: any) => {
        if (obj.code === 1) {
          successToast(obj.msg);
          showLoading();
          this.getVehicleList();
          this.getPlateList();
        } else {
          showToast(obj.msg);
        }
      });
    },
  },
});
